#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <math.h>
#include "ds1338c.h"
#include "encode.h"

#define BCD_TO_DEC(val) (((val)&15) + ((val)>>4)*10)
#define DEC_TO_BCD(val)	((((val)/10)<<4) + (val)%10)

int main()
{
	int dev;
	ds_rtc_time time;
	ds_rtc_time get_time;
	ds_rtc_time bcd_time;
	write_reg_value	write_reg;
	unsigned char reg;
	unsigned char value;

	#ifdef HI3511
	dev = open("/dev/misc/ds1338", O_RDONLY);
	#else
	dev = open("/dev/ds1338", O_RDONLY);
	#endif
	if (dev <= 0) {
		printf("ds1338 device open fail\n");
		exit(0);
	}
	
	/* read all register */
	ioctl(dev, DS1338_RTC_READ_ALL_REG);

	/* get current time */
	//ioctl(dev, DS1338_RTC_READ_TIME);

	/* set time */
	time.year = (unsigned char)0x11;
	time.month = (unsigned char)0x12;
	time.day = (unsigned char)0x31;
	time.hour = (unsigned char)0x14;
	time.minute = (unsigned char)0x52;
	time.second = (unsigned char)0x00;

	//printf("\t[application][%s:%d][0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x]\n",__FUNCTION__,
	//		__LINE__, time.year, time.month, time.date, time.hour, time.minute, time.second);
	//sleep(1);
	//ioctl(dev, DS1338_RTC_WRITE_TIME,&time);	

	/* set single reg */
	write_reg.reg = YEAR;
	write_reg.value = 0x12;		// 2012
	//ioctl(dev, DS1338_RTC_WRITE_SINGLE_REG,&write_reg);	

	/* read single reg */
	reg = MONTH;
	value = ioctl(dev, DS1338_RTC_READ_SINGLE_REG,&reg);	
	printf("\t reg = 0x%02x value = 0x%02x = %d\n", reg, value, value);

	while (0) {
		ioctl(dev, DS1338_RTC_GET_TIME, &get_time);	// get time
		#if 0
		bcd_time.year = BCD_TO_DEC(get_time.year);
		bcd_time.month = BCD_TO_DEC(get_time.month);
		bcd_time.date = BCD_TO_DEC(get_time.date);
		bcd_time.hour = BCD_TO_DEC(get_time.hour);
		bcd_time.minute = BCD_TO_DEC(get_time.minute);
		bcd_time.second = BCD_TO_DEC(get_time.second);
		#endif
		//bcd_time.second = BCD_TO_DEC(((get_time.second >> 4) + 48) * 10 + ((get_time.second & 0x0f)+48));
		//orin_time.second = ((orin_time.second >> 4) * 10 + (get_time.second & 0x0f));

		//printf("(BCD) 20%d 年 %d 月 %d 日 %d:%d:%d\n", bcd_time.year, 
		//							bcd_time.month,bcd_time.date,bcd_time.hour,bcd_time.minute,bcd_time.second);
		//printf("20%d 年 %d 月 %d 日 %d:%d:%d\n", get_time.year, 
		//							get_time.month,get_time.date,get_time.hour,get_time.minute,get_time.second);
		printf("20%x 年 %x 月 %x 日 %02x:%02x:%02x\n", get_time.year, 
									get_time.month,get_time.day,get_time.hour,get_time.minute,get_time.second);
		sleep(1);
		//ioctl(dev, DS1338_RTC_READ_ALL_REG);
	}

	close(dev);

	return 0;
}
